package com.bh.extend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.annotation.DataDictClass;
import com.bh.common.constant.Symbol;
import com.bh.common.exception.ServiceException;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.bean.BeanValidators;
import com.bh.common.utils.spring.SpringUtils;
import com.bh.extend.convert.JcCustomerPriceConvert;
import com.bh.extend.domain.JcCustomer;
import com.bh.extend.domain.JcCustomerPrice;
import com.bh.extend.domain.JcCustomerVolumePrice;
import com.bh.extend.mapper.JcCustomerPriceMapper;
import com.bh.extend.service.IJcCustomerPriceService;
import com.bh.extend.service.IJcCustomerService;
import com.bh.extend.vo.JcCustomerPriceQueryVo;
import com.bh.extend.vo.JcCustomerPriceVo;
import com.bh.kysys.domain.JcSysOrganization;
import com.bh.kysys.service.IJcSysOrganizationService;
import com.bh.order.domain.JcOrder;
import com.bh.order.domain.JcServerZone;
import com.bh.order.mapper.JcServerZoneMapper;
import com.bh.order.service.IJcServerZoneService;
import com.bh.order.vo.JcServerZoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.*;

/**
 * 客户单价Service业务层处理
 *
 * @author slx
 * @date 2023-04-03
 */

@Service
public class JcCustomerPriceServiceImpl extends ServiceImpl<JcCustomerPriceMapper, JcCustomerPrice> implements IJcCustomerPriceService {
    @Autowired
    private JcCustomerPriceMapper jcCustomerPriceMapper;
    @Autowired
    private IJcServerZoneService jcServerZoneService;
    @Autowired
    private IJcSysOrganizationService sysOrganizationService;
    @Autowired
    private IJcCustomerService jcCustomerService;
    @Autowired
    private JcServerZoneMapper jcServerZoneMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private JcCustomerPriceConvert jcCustomerPriceConvert;

    @Override
    public JcCustomerPrice selectJcCustomerPriceInfo(JcCustomerPriceQueryVo queryVo) {
        JcCustomerPrice price = null;
        if (queryVo != null) {
            price = jcCustomerPriceMapper.selectJcCustomerPriceInfo(queryVo);
        }
        return price;
    }

    /**
     * 查询客户单价
     *
     * @param id 客户单价主键
     * @return 客户单价
     */
    @DataDictClass
    @Override
    public JcCustomerPrice selectJcCustomerPriceById(Long id) {
        JcCustomerPrice customerPrice = jcCustomerPriceMapper.selectJcCustomerPriceById(id);
        if (customerPrice != null) {
            JcServerZone from = jcServerZoneService.selectJcServerZoneById(customerPrice.getFromServerZoneId());
            if (from != null) {
                customerPrice.setFromServerZoneIdDtLabel(from.getJcZoneIdDtLabel());
            }
            JcServerZone to = jcServerZoneService.selectJcServerZoneById(customerPrice.getToServerZoneId());
            if (to != null) {
                customerPrice.setToServerZoneIdDtLabel(to.getJcZoneIdDtLabel());
            }
            if (StringUtils.isNotEmpty(customerPrice.getModel())) {
                customerPrice.setModels(customerPrice.getModel().split(Symbol.COMMA));
            }
        }
        return customerPrice;
    }

    /**
     * 查询客户单价列表
     *
     * @param jcCustomerPrice 客户单价
     * @return 客户单价
     */
    @DataDictClass
    @Override
    public List<JcCustomerPrice> selectJcCustomerPriceList(JcCustomerPrice jcCustomerPrice) {
        jcCustomerPrice.setJcOrganizationId(SecurityUtils.getOrgId());
        List<JcCustomerPrice> list = jcCustomerPriceMapper.selectJcCustomerPriceList(jcCustomerPrice);
        for (JcCustomerPrice customerPrice : list) {
            JcServerZone from = jcServerZoneService.selectJcServerZoneById(customerPrice.getFromServerZoneId());
            if (from != null) {
                customerPrice.setFromServerZoneIdDtLabel(from.getName());
            }
            JcServerZone to = jcServerZoneService.selectJcServerZoneById(customerPrice.getToServerZoneId());
            if (to != null) {
                customerPrice.setToServerZoneIdDtLabel(to.getName());
            }
        }
        return list;
    }

    @DataDictClass
    @Override
    public List<JcCustomerPriceVo> selectJcCustomerPriceVoList(JcCustomerPrice jcCustomerPrice) {
        jcCustomerPrice.setJcOrganizationId(SecurityUtils.getOrgId());
        List<JcCustomerPriceVo> voList = new ArrayList<>();
        List<JcCustomerPrice> list = jcCustomerPriceMapper.selectJcCustomerPriceList(jcCustomerPrice);
        for (JcCustomerPrice customerPrice : list) {
            // 转换
            JcCustomerPriceVo jcCustomerPriceVo = jcCustomerPriceConvert.toVo(customerPrice);
            JcServerZone from = jcServerZoneService.selectJcServerZoneById(jcCustomerPriceVo.getFromServerZoneId());
            if (from != null) {
                jcCustomerPriceVo.setFromServerZoneIdName(from.getName());
            }
            JcServerZone to = jcServerZoneService.selectJcServerZoneById(jcCustomerPriceVo.getToServerZoneId());
            if (to != null) {
                jcCustomerPriceVo.setToServerZoneIdName(to.getName());
            }
            voList.add(jcCustomerPriceVo);
        }
        return voList;
    }

    @Override
    public List<JcCustomerVolumePrice> selectJcCustomerVolumePriceByPriceId(Long priceId) {
        return jcCustomerPriceMapper.selectJcCustomerVolumePriceByPriceId(priceId);
    }

    @Override
    public String importData(List<JcCustomerPriceVo> list, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<JcCustomerPrice> insertPrices = new ArrayList<>();
        List<JcCustomerPrice> updatePrices = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JcCustomerPriceVo customerPriceVo = list.get(i);
            try {
                // 验证是否存在这个用户
                JcCustomerPrice price = null;
                if (customerPriceVo.getId() != null) {
                    price = jcCustomerPriceMapper.selectById(customerPriceVo.getId());
                }
                if (StringUtils.isNull(price)) {
                    BeanValidators.validateWithException(validator, customerPriceVo);
                    price = jcCustomerPriceConvert.toDO(customerPriceVo);
                    JcCustomer customer = jcCustomerService.selectJcCustomerByName(customerPriceVo.getCustomerName());
                    if (customer == null) {
                        throw new ServiceException("客户名称" + customerPriceVo.getCustomerName() + "不正确！");
                    }
                    price.setCustomerId(customer.getId());
                    price.setJcOrganizationId(customer.getJcOrganizationId());
                    price.setModel("TOOK,TRANS,DELIVERY");
                    //出发网点
                    JcSysOrganization organization = sysOrganizationService.selectJcSysOrganizationByName(customerPriceVo.getFromOrgName());
                    if (organization == null) {
                        throw new ServiceException("出发网点" + customerPriceVo.getFromOrgName() + "不正确！");
                    }
                    price.setFromOrg(organization.getId());
                    //出发运点
                    JcServerZone startZone = jcServerZoneService.selectJcServerZoneByName(customerPriceVo.getFromServerZoneIdName(), organization.getId());
                    if (startZone != null) {
                        price.setFromServerZoneId(startZone.getId());
                    } else {
                        JcServerZoneVo jcServerZone = new JcServerZoneVo();
                        jcServerZone.setZones(customerPriceVo.getFromServerZoneIdName());
                        jcServerZone.setOrgId(organization.getId());
                        Long fromServerZoneId = jcServerZoneService.insertJcServerZoneByAddress(jcServerZone);
                        price.setFromServerZoneId(fromServerZoneId);
                    }
                    //目的网点
                    JcSysOrganization toOrganization = sysOrganizationService.selectJcSysOrganizationByName(customerPriceVo.getToOrgName());
                    if (toOrganization == null) {
                        throw new ServiceException("目的网点" + customerPriceVo.getToOrgName() + "不正确！");
                    }
                    price.setToOrg(toOrganization.getId());
                    //目的运点
                    JcServerZone endZone = jcServerZoneService.selectJcServerZoneByName(customerPriceVo.getToServerZoneIdName(), toOrganization.getId());
                    if (endZone != null) {
                        price.setToServerZoneId(endZone.getId());
                    } else {
                        JcServerZoneVo jcServerZone = new JcServerZoneVo();
                        jcServerZone.setZones(customerPriceVo.getToServerZoneIdName());
                        jcServerZone.setOrgId(toOrganization.getId());

                        Long toServerZoneId = jcServerZoneService.insertJcServerZoneByAddress(jcServerZone);
                        price.setToServerZoneId(toServerZoneId);
                    }
                    price.setCreateTime(new Date());
                    price.setCreateBy(operName);
//                    jcCustomerPriceMapper.insert(price);
                    insertPrices.add(price);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、第 ").append(i + 1).append(" 条数据导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, customerPriceVo);
//                    jcCustomerPriceMapper.updateById(price);
                    updatePrices.add(price);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、第 ").append(i + 1).append(" 条数据更新成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第 " + (i + 1) + " 条数据导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
                e.printStackTrace();
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            if (insertPrices.size() > 0) {
                SpringUtils.getBean(this.getClass()).saveBatch(insertPrices);
            }
            if (updatePrices.size() > 0) {
                SpringUtils.getBean(this.getClass()).updateBatchById(updatePrices);
            }
            if(successNum > 0) {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            } else {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            }
        }
        return successMsg.toString();
    }

    /**
     * 新增客户单价
     *
     * @param jcCustomerPrice 客户单价
     * @return 结果
     */
    @Override
    public int insertJcCustomerPrice(JcCustomerPrice jcCustomerPrice) {
        if (jcCustomerPrice.getModels() != null && jcCustomerPrice.getModels().length > 0) {
            String model = StringUtils.join(jcCustomerPrice.getModels(), ",");
            jcCustomerPrice.setModel(model);
        }
        JcCustomerPriceQueryVo queryVo = new JcCustomerPriceQueryVo();
        queryVo.setCustomerId(jcCustomerPrice.getCustomerId());
        queryVo.setFromServerZoneId(jcCustomerPrice.getFromServerZoneId());
        queryVo.setToServerZoneId(jcCustomerPrice.getToServerZoneId());
        queryVo.setFromOrg(jcCustomerPrice.getFromOrg());
        queryVo.setToOrg(jcCustomerPrice.getToOrg());
        JcCustomerPrice customerPrice = jcCustomerPriceMapper.selectJcCustomerPriceInfo(queryVo);
        if (customerPrice != null) {
            throw new ServiceException("客户单价已存在");
        }
        jcCustomerPrice.setCreateTime(DateUtils.getNowDate());
        jcCustomerPrice.setCreateBy(SecurityUtils.getUsername());
        if (jcCustomerPrice.getPickupPrice() == null || jcCustomerPrice.getPickupPrice().compareTo(BigDecimal.ZERO) == 0) {
            // 直接將已有数据获取并存储
            JcCustomerPrice pickUpPrice = jcCustomerPriceMapper.selectPikupPriceByCustomerId(jcCustomerPrice.getCustomerId());
            if (pickUpPrice != null) {
                jcCustomerPrice.setPickupPrice(pickUpPrice.getPickupPrice());
            }
        }
        int rows = jcCustomerPriceMapper.insert(jcCustomerPrice);
        insertJcCustomerVolumePrice(jcCustomerPrice);
        return rows;
    }

    /**
     * 修改客户单价
     *
     * @param jcCustomerPrice 客户单价
     * @return 结果
     */
    @Override
    public int updateJcCustomerPrice(JcCustomerPrice jcCustomerPrice) {
        JcCustomerPriceQueryVo queryVo = new JcCustomerPriceQueryVo();
        queryVo.setCustomerId(jcCustomerPrice.getCustomerId());
        queryVo.setFromServerZoneId(jcCustomerPrice.getFromServerZoneId());
        queryVo.setToServerZoneId(jcCustomerPrice.getToServerZoneId());
        queryVo.setFromOrg(jcCustomerPrice.getFromOrg());
        queryVo.setToOrg(jcCustomerPrice.getToOrg());
        JcCustomerPrice customerPrice = jcCustomerPriceMapper.selectJcCustomerPriceInfo(queryVo);
        if (customerPrice != null && !Objects.equals(customerPrice.getId(), jcCustomerPrice.getId())) {
            throw new ServiceException("客户单价已存在");
        }
        jcCustomerPrice.setUpdateBy(SecurityUtils.getUsername());
        jcCustomerPrice.setUpdateTime(DateUtils.getNowDate());
        if (jcCustomerPrice.getPickupPrice() == null || jcCustomerPrice.getPickupPrice().compareTo(BigDecimal.ZERO) == 0) {
            // 直接將已有数据获取并存储
            JcCustomerPrice pickUpPrice = jcCustomerPriceMapper.selectPikupPriceByCustomerId(jcCustomerPrice.getCustomerId());
            if (pickUpPrice != null) {
                jcCustomerPrice.setPickupPrice(pickUpPrice.getPickupPrice());
            }
        }
        jcCustomerPriceMapper.deleteJcCustomerVolumePriceByPriceId(jcCustomerPrice.getId());
        insertJcCustomerVolumePrice(jcCustomerPrice);
        return jcCustomerPriceMapper.updateById(jcCustomerPrice);
    }

    /**
     * 批量删除客户单价
     *
     * @param ids 需要删除的客户单价主键
     * @return 结果
     */
    @Override
    public int deleteJcCustomerPriceByIds(Long[] ids) {
        jcCustomerPriceMapper.deleteJcCustomerVolumePriceByPriceIds(ids);
        return jcCustomerPriceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除客户单价信息
     *
     * @param id 客户单价主键
     * @return 结果
     */
    @Override
    public int deleteJcCustomerPriceById(Long id) {
        jcCustomerPriceMapper.deleteJcCustomerVolumePriceByPriceId(id);
        return jcCustomerPriceMapper.deleteById(id);
    }

    /**
     * 新增分段体积价格信息
     *
     * @param jcCustomerPrice 客户单价对象
     */
    public void insertJcCustomerVolumePrice(JcCustomerPrice jcCustomerPrice) {
        List<JcCustomerVolumePrice> jcCustomerVolumePriceList = jcCustomerPrice.getJcCustomerVolumePriceList();
        Long id = jcCustomerPrice.getId();
        if (StringUtils.isNotNull(jcCustomerVolumePriceList)) {
            List<JcCustomerVolumePrice> list = new ArrayList<>();
            // 必须保证不出现重复并且相等
            Long endVolume = 0L;
            for (JcCustomerVolumePrice jcCustomerVolumePrice : jcCustomerVolumePriceList) {
                if (!jcCustomerVolumePrice.getStartValue().equals(endVolume)) {
                    throw new ServiceException("分段体积价格数据错误,请保证数据从0开始，并将每一段数据首尾呼应!");
                }
                // 必须保证不出现重复
                jcCustomerVolumePrice.setPriceId(id);
                list.add(jcCustomerVolumePrice);
                endVolume = jcCustomerVolumePrice.getEndValue();
            }
            if (list.size() > 0) {
                jcCustomerPriceMapper.batchJcCustomerVolumePrice(list);
            }
        }
    }
}
